﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SJ.Platform.Extend.IOC.CurrentUser;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.OrgManager;
using SJ.Platform.Extend.Request;
using SJ.Platform.Extend.Response;
using System.Linq.Expressions;
using SJ.Platform.Extend.ModelExtend;
using System.Security.Cryptography;
using Amazon.Runtime.Internal;
using SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Sys;
using SJ.Platform.EFCore.Common;

namespace SJ.Platform.Api.Controllers.OrgManager
{
    /// <summary>
    /// 组织机构操作接口
    /// </summary>
    [Route(GlobalVariableHandle.Scope_Api + "/Org")]
    [ApiController]
    [Authorize(GlobalVariableHandle.Scope_Api)]
    public class OrgManagerController : ControllerBase
    {
        private readonly Sys_OrgHandle sys_OrgHandle;
        private readonly Sys_UserHandle sys_UserHandle;
        private readonly ICurrentUser _currentUser;
        private readonly SJDBContext _dbContext;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库</param>
        /// <param name="currentUser">当前用户</param>
        public OrgManagerController(SJDBContext dbContext, ICurrentUser currentUser)
        {
            sys_OrgHandle = new Sys_OrgHandle(dbContext);
            sys_UserHandle = new Sys_UserHandle(dbContext);
            _currentUser = currentUser;
            _dbContext = dbContext;
        }

        /// <summary>
        /// 新增组织机构
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("CreateOrgAsync")]
        public async Task<IActionResult> CreateOrgAsync([FromBody] SysOrg model)
        {
            var Org = new SysOrg
            {
                Id = Guid.NewGuid().ToString(),
                OrgName = model.OrgName,
                Pid = model.Pid,
                OrgType = model.OrgType,
                Mark = model.Mark,
                AddTime = DateTime.Now,
                AddUserId = _currentUser.UserId,
                EditTime = DateTime.Now,
                EditUserId = _currentUser.UserId
            };
            try
            {
                bool result = await sys_OrgHandle.CreateAsync(Org);
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "组织机构添加" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "组织机构添加失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 修改组织机构
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("UpdateOrgAsync")]
        public async Task<IActionResult> UpdateOrgAsync([FromBody] SysOrg model)
        {
            try
            {
                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_dbContext, async () =>
                {
                    var Org = new SysOrg
                    {
                        Id = model.Id,
                        OrgName = model.OrgName,
                        Pid = model.Pid,
                        OrgType = model.OrgType,
                        Mark = model.Mark,
                        EditTime = DateTime.Now,
                        EditUserId = _currentUser.UserId
                    };

                    return await sys_OrgHandle.UpdateAsync(Org) && await sys_UserHandle.UpdateOrgAsync(Org.Id, Org.OrgName);
                });
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "组织机构修改" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "组织机构修改失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 删除组织机构
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        [HttpGet("DeleteByOrgIdAsync/{orgId}")]
        public async Task<IActionResult> DeleteByOrgIdAsync(string orgId)
        {
            try
            {
                bool result = await sys_OrgHandle.DeleteByIdAsync(orgId);
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "删除组织机构" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "删除组织机构失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 根据OrgId获取所有组织机构
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        [HttpGet("GetAllOrgByOrgId/{orgId}/{searchAll}")]
        public async Task<IActionResult> GetAllOrgByOrgId(string orgId,int searchAll)
        {
            try
            {
                if (searchAll==1)
                {
                    var org = await sys_OrgHandle.GetAllAsync(o => string.IsNullOrWhiteSpace(o.Pid));
                    orgId = org[0].Id;
                }
                var result = await sys_OrgHandle.GetAllByOrgId(orgId);

                return Ok(ApiNormalResponse<List<SysOrgExtend>>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<SysOrg>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new List<SysOrg> { }));
            }
        }

        /// <summary>
        /// 根据OrgId获取所有组织机构
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("GetAllAndChildAsync")]
        public async Task<IActionResult> GetAllAndChildAsync([FromBody] ApiPageQueryRequest<SysOrg> request)
        {
            try
            {
                SysOrg condition = request.Condition;
                var result = await sys_OrgHandle.GetAllAndChildAsync((int)request.PageIndex, (int)request.PageSize, condition);

                return Ok(ApiPageQueryResponse<List<SysOrgExtend>>.SetResponse(ApiResponseStatus.Success, "查询成功", (int)request.PageIndex, (int)request.PageSize, result.count, result.orgs)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiPageQueryResponse<List<SysOrgExtend>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, (int)request.PageIndex, (int)request.PageSize, 0, new List<SysOrgExtend> { }));
            }
        }

        /// <summary>
        /// 分页获取所有组织机构
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("GetAllOrgAsync")]
        public async Task<IActionResult> GetAllOrgAsync([FromBody] ApiPageQueryRequest<SysOrg> request)
        {
            try
            {
                var result = await sys_OrgHandle.GetAllAsync((int)request.PageIndex, (int)request.PageSize, ApiPageQueryRequest<SysOrg>.GenerateCondition(request.Condition));

                return Ok(ApiPageQueryResponse<List<SysOrg>>.SetResponse(ApiResponseStatus.Success, "查询成功", (int)request.PageIndex, (int)request.PageSize, result.count, result.orgs)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiPageQueryResponse<List<SysOrg>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, (int)request.PageIndex, (int)request.PageSize, 0, new List<SysOrg> { }));
            }
        }
    }
}
